package com.bw.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bw.domain.JWTUtils;
import com.bw.domain.Result;
import com.bw.domain.SysUser;
import com.bw.mapper.SysUserMapper;
import com.bw.service.SysUserService;
import com.bw.service.impl.SysUserServiceImpl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author bobo棒
 * @date 2024年04月15日 10:48
 */

@CrossOrigin
@RestController
@RequestMapping("auth")
public class AuthController {
    @Autowired
    SysUserService sysUserService;
    @Autowired
    RedisTemplate redisTemplate;


    @RequestMapping("login")
    public Result login(@RequestBody SysUser sysUser){

        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getUsername,sysUser.getUsername());
        SysUser dbUser = sysUserService.getOne(wrapper);
        if(null==dbUser){
            return Result.fail("无此用户");
        }

        if(!dbUser.getPassword().equals(sysUser.getPassword())){
            return Result.fail("密码错误");
        }
        //登录成功
        String token = JWTUtils.createToken(dbUser.getId(), 60 * 5);

        //登录信息保存到redis（要求：合理设计redis的key，确保key的唯一性）
        redisTemplate.opsForValue().set("user:"+dbUser.getId(),dbUser);
        return Result.success(token);
    }
}
